package com.good.shopping.order.conf;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  Feign异步调用丢失请求头问题
 *      由于RequestContextHolder使用ThreadLocal共享数据，
 *      所以在开启异步时获取不到老请求的信息，自然也就无法共享cookie了。
 *      在这种情况下，我们需要在开启异步的时候将老请求的RequestContextHolder的数据设置进去
 * https://www.cnblogs.com/gaomanito/p/12515526.html
 * @author shengren.yan
 * @create 2022-03-17
 */
@Configuration
public class FeignConfig {


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null) {
                        //2、同步请求头的数据（主要是cookie）
                        //把老请求的cookie值放到新请求上来，进行一个同步
                        String cookie = request.getHeader("Cookie");
                        template.header("Cookie", cookie);
                    }
                }
            }
        };

        return requestInterceptor;
    }


}
